import config from 'config'
import httpFetch from 'share/httpFetch'
import errorMessage from 'share/errorMessage';
import {messages, getTime} from "share/common";
import {message, Modal} from 'antd';
import axios from 'axios';
import CryptoJS from 'crypto-js';
import JSEncrypt from 'jsencrypt/bin/jsencrypt';
import configureStore from "stores";

let CryptoJSKey = CryptoJS.enc.Utf8.parse('XDYqtdlcnMRchrgD');
let CryptoJSkeyIv = CryptoJS.enc.Utf8.parse('Ai2ecTvyERY6t8w8');
let CryptoJSEnCodeMode = {
  iv: CryptoJSkeyIv,
  mode: CryptoJS.mode.CBC,
  padding: CryptoJS.pad.Pkcs7
};
export default {
  // 加密
  enCodePassword(word) {
    return CryptoJS.AES.encrypt(word, CryptoJSKey, CryptoJSEnCodeMode).toString();
  },
  // 解密
  deCodePassword(ciphertext) {
    let bytes = CryptoJS.AES.decrypt(ciphertext, CryptoJSKey, CryptoJSEnCodeMode);
    return bytes.toString(CryptoJS.enc.Utf8);
  },
  encrypt(login, publicKey){
    let encrypt = new JSEncrypt();
    encrypt.setPublicKey(publicKey);
    return encrypt.encrypt(login);
  },
  //获取验证码
  getConfirmCode(login, attachmentOID, verifyCode) {
    /*
    login: 手机号或邮箱地址
    type: 手机号还是邮箱
     */
    let params = {
      login: this.enCodePassword(login),
      attachmentOID,
      verifyCode,
      client: "web"
    };
    let time = (new Date()).getTime();
    return new Promise((resolve, reject) => {
      httpFetch.get(`${config.baseUrl}/api/refactor/account/reset_password/init/v3?time=${time}`, params)
        .then(res => {
          resolve(res);
        })
        .catch(err => {
          errorMessage(err.response);
          reject(err);
        })
    })
  },

  // 获取密码设置规则
  getPasswordRule: function (mobile_or_email) {
    return (this.getPasswordRuleV2(mobile_or_email));
  },
  // 校验密码
  regPasswordByRule: function (password, password_rule) {
    //先验证长度
    if (password.length < parseInt(password_rule.minLength)) {
      //密码长度不能小于{min}位
      message.error(messages('dashboard.key104', {arg1: password_rule.minLength}/*密码长度不能小于{arg1}位*/));
      return false;
    }
    if (password.length > parseInt(password_rule.maxLength)) {
      // 密码长度不能大于{max}位
      message.error(messages('dashboard.key105', {arg1: password_rule.maxLength}/*密码长度不能大于{arg1}位*/));
      return false;
    }
    //验证数字
    let regexNum = /^.*[0-9].*$/;
    //验证小写字母
    let regexLowerCase = /^.*[a-z].*$/;
    //验证大写字母
    let regexUpperCase = /^.*[A-Z].*$/;
    //验证特殊字符
    let regexSpecialChar = /^.*[~!@#\$%\^&\*\(\)_+\-=\[\]\{\}\\\|\'\";:,\<\.\>\/\?\s+].*$/;
    if (password_rule.isNeedNumber) {
      let val = regexNum.test(password);
      if (!val) {
        // 密码需要包含数字
        message.error(messages('dashboard.key83'/*密码需要包含数字*/));
        return false;
      }
    }
    if (password_rule.isNeedLowercase) {
      let val = regexLowerCase.test(password);
      if (!val) {
        // 密码需要包含小写字母
        message.error(messages('dashboard.key84'/*密码需要包含小写字母*/));
        return false;
      }
    }
    if (password_rule.isNeedUppercase) {
      let val = regexUpperCase.test(password);
      if (!val) {
        // 密码需要包含大写字母
        message.error(messages('dashboard.key85'/*密码需要包含大写字母*/));
        return false;
      }
    }
    if (password_rule.isNeedSpecialChar) {
      let val = regexSpecialChar.test(password);
      if (!val) {
        // 密码需要包含特殊字符
        message.error(messages('dashboard.key86'/*密码需要包含特殊字符*/));
        return false;
      }
    }
    //如果上面都通过
    return true;
  },
  //判断验证码是否正确
  judgeConfirmCode(login, token) {
    let params = {
      login: this.enCodePassword(login),
      token,
      client: "web",
    };
    return new Promise((resolve, reject) => {
      axios({
        url: config.baseUrl + `/api/refactor/account/reset_password/check/v3`,
        method: 'POST',
        data: params,
      }).then(res => {
        resolve(res)
      }).catch(err => {
        errorMessage(err.response);
        reject(err);
      })
    })
  },
  //确认新密码
  confirmNewPassword(login, token, newPass) {
    let params = {
      login: this.enCodePassword(login),
      token,
      client: "web",
      newPassword: this.enCodePassword(newPass)
    };
    return new Promise((resolve, reject) => {
      axios({
        url: config.baseUrl + `/api/refactor/account/reset_password/finish/v3`,
        method: 'POST',
        data: params,
      }).then(res => {
        resolve(res)
      }).catch(err => {
        errorMessage(err.response);
        reject(err);
      })
    });
  },

  delLoginErr(err) {
    //这个地方要前端一个一个处理，
    //后端说是登录太复杂，情况太多，
    // 对于其他接口，后端给什么错误信息，前端就提示什么错误信息
    let em = err.response.data.error_description;
    let sso_desc = err.response.data.error;
    //需要添加的提示
    if (err.response.data) {
      if(em === "special.login"){
        message.error(messages('login.key52')/*无效登录方式*/);
        return;
      }
      if(sso_desc === "validation_fail"){
        // 单点登录报错，就直接报错,其他登录方式没有这个字段
        message.error(em);
        return;
      }
      if(em === 'wechat.custom.install'){
        //这种不用提示
        return;
      }
      if (em === 'User account has expired') {
        message.error(messages('dashboard.key45'/*账号已过期*/));
        return;
      }
      if (em === 'wechat.install.fail') {
        message.error(messages('login.key51')/*微信安装失败，请联系管理员*/);
        return;
      }
      if (em === 'user.not.activated') {
        message.error(messages('login.key61')/*您的账号尚未激活，请激活后再进行使用*/);
        return;
      }
      if (em === 'Bad credentials') {
        // 用户名或密码错误 bug21498
        message.error(messages('dashboard.key47'/*用户名或密码错误*/));
        return;
      }
      if (em === 'email.not.bind') {
        message.error(messages('dashboard.key48'/*邮箱号未绑定*/));
        return;
      }
      if (em === 'mobile.not.bind') {
        message.error(messages('dashboard.key49'/*手机号未绑定*/));
        return;
      }
      if (em === 'user.not.found') {
        message.error(messages('dashboard.key50'/*用户不存在*/));
        return;
      }
      if (em === 'user.is.locked') {
        message.error(messages('dashboard.key51'/*账号已锁定，请找回密码*/));
        return;
      }
      if (em === 'related.multi.user') {
        message.error(messages('dashboard.key52'/*该账号关联多个未知用户*/));
        return;
      }
      if (em === 'user.password.expired') {
        message.error(messages('dashboard.key53'/*密码已过期,请找回密码*/));
        return;
      }
      if (em === 'user.was.leaved') {
        message.error(messages('dashboard.key54'/*用户已离职*/));
        return;
      }
      if (em === 'User is disabled') {
        //单点登录场景
        message.error(messages('dashboard.key55'/*用户未激活*/));
        return;
      }
      if (em === 'corp.user.invalid') {
        //单点登录场景
        message.error(messages('dashboard.key47'/*用户名或密码错误*/));
        return;
      }
      if (em === 'corp.connection.fail') {
        //单点登录场景
        message.error(messages('dashboard.key56'/*企业登录连接失败*/));
        return;
      }
      if (em === 'corp.not.activated') {
        //微信扫码登录错误 1
        Modal.warning({
          title: messages('dashboard.key106')/*登录提示*/,
          content: messages('dashboard.key107')/*未在企业微信中开通汇联易，如需开通请联系公司管理员*/,
        });
        return;
      }
      if (em === 'user.not.bind') {
        return;
      }
      if (em === 'user.wechat.first') {
        //微信扫码登录错误 2
        Modal.warning({
          title: messages('dashboard.key106')/*登录提示*/,
          content: messages('dashboard.key108')/*请先在【企业微信APP-工作台】点击汇联易应用，再返回扫码页面扫描二维码登录*/,
        });
      } else {
        message.error(messages('dashboard.key44'/*哦呼，服务器出了点问题，请联系管理员或稍后再试:(*/));
      }
    }
  },
  //是否是自己的域名
  isSelfDomain: function(hostName){
    let selfNames = [
      new RegExp(/^console.huilianyi.com/g),
      new RegExp(/^stage.huilianyi.com/g),
      new RegExp(/^uat.huilianyi.com/g),
      new RegExp('localhost'),
      new RegExp(/\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3}/g),//ip 也无须校验登录
    ]
    let res = selfNames.filter(item=>{
      return hostName.match(item)
    })
    return !!res.length;
  },
  //获取登录二维码
  //获取UUID
  getQcode: function () {
    return axios({
      headers: {"Cache-Control": "no-cache", "Pragma": "no-cache", "Expires": -1},
      url: config.baseUrl + '/auth/api/qr/authorization?time=' + getTime(),
      method: 'GET',
    })
  },
  //二维码扫描轮询(扫描之后，未点击确认)
  getQcodeAuthorization: function (UUID) {
    return axios({
      headers: {"Cache-Control": "no-cache", "Pragma": "no-cache", "Expires": -1},
      url: config.baseUrl + '/auth/api/qr/authorization/' + UUID,
      method: 'GET',
    })
  },
  //哪一种登录方式
  loginDecide: function () {
    let domainName = window.location.hostname;
    return axios({
      url: config.ssoUrl + '/sso/loginDecide?domainName=' + domainName,
      method: 'GET',
    })
  },
  //企业登录
  loginDecideV2: function (account, redirect_url) {
    let publicKey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCDAxLcb5T5WrS1RfVCy6YcmE8Ue2y33mwWnE+K5y1B61eXx0wcS4yoNEWC/7Mmg405I5SVTWSxFjgkYE5Bmd2O2jiDV/TGPWIVQrn5L4lIypbCnb5isHI+udpT0jPyf4ixdzsAu8FWcDgL/DXBO6ieKQ0gdngg5Tce7Frcumi3HQIDAQAB';
    let params = {
      redirect_url: redirect_url,
      account: this.encrypt(account, publicKey)
    };
    return axios({
      url: config.baseUrl + '/sso/v3/login',
      method: 'GET',
      params: params
    })
  },
  // 密码输入错误的时候，调用
  loginErrorCounts: function (username) {
    return axios({
      url: config.baseUrl + '/api/refactor/account/loginErrorCounts' + username,
      method: 'POST',
    })
  },

  testPhoneOrEmail: function (phoneNum) {
    let type = "";
    let phoneReg = new RegExp('^[0-9]{11}$');
    let emailReg = new RegExp('^[A-Za-z0-9!#$%&\'*+\\/=?^_`{|}~.-]+@[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?(\\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)*$');
    if (phoneReg.test(phoneNum) || emailReg.test(phoneNum)) {
      type = phoneReg.test(phoneNum) ? messages('login.key5'/*手机*/) : messages('login.key6'/*邮箱*/);
      return {pass: true, type: type};
    } else {
      message.error(messages('login.key7'/*请输入正确的手机号或邮箱地址*/));
      return {pass: false, type: type};
    }
  },

  getPasswordRuleV2(username, protocol) {
    let params = {
      client: "web",
      needProtocolI18n: protocol === undefined ? true : protocol,
      username: this.enCodePassword(username),
    };
    //建议能用邮箱获取,就邮箱,因为手机可能被修改
    return new Promise((resolve, reject) => {
      httpFetch.post(`${config.baseUrl}/api/refactor/password/rule/topic/v2`, params)
        .then((res) => {
          resolve(res)
        })
        .catch((err) => {
          errorMessage(err.response);
          reject(err);
        })
    })
  },
  getLoginWayConfig: function (language, loginWayAllObj, self, pathLoginWay) {
    let params = {
      domain: window.location.protocol + "//" + window.location.hostname,
      // domain: "http:%2F%2Fapiuat.huilianyi.com",
      clientCode: "WEB",
      language,
    };
    return new Promise((resolve, reject) => {
      // axios({
      //   url: config.baseUrl + "/operationservice/public/merge/maintenanceAnnounce",
      //   method: "GET",
      //   params: params,
      //   timeout: 1000,
      // }).then(res => {
      //   let data = {
      //     hasCodeLogin: false,
      //     loginWayList: [],
      //     codeLoginMessage: messages('login.key48')/*二维码登录*/,
      //   };
      //   if(res.data && res.data.loginConfigs && res.data.loginConfigs.length){
      //     res.data.loginConfigs.map(item => {
      //       if (item.loginCode === "QR_CODE") {
      //         data.hasCodeLogin = true;
      //         data.codeLoginMessage = item.loginName;
      //       }else {
      //         let param = loginWayAllObj[item.loginCode](self);
      //         param.message = item.loginName;
      //         if(item.loginIcon){
      //           param.icon = item.loginIcon
      //         }
      //         data.loginWayList.push(param);
      //       }
      //     });
      //   }else{
      //     data.loginWayList.push(loginWayAllObj["ACCOUNT"](self));
      //   }
      //   data.loginWayList[0].active = true;
      //   resolve(data)
      // }).catch(err => {
      //   errorMessage(err.response);
      //   reject(err);
      // })

      let resData = {
        "maintenanceAnnounce":null,
        "loginConfigs":[
          {
            "i18n":null,
            "id":"4",
            "loginIcon":"",
            "client":"WEB",
            "cloudEnv":"ALY",
            "loginCode":"QR_CODE",
            "loginName":"二维码登录",
            "sortOrder":1,
            "enabled":true
          },
          {
            "i18n":null,
            "id":"5",
            "loginIcon":"",
            "client":"WEB",
            "cloudEnv":"ALY",
            "loginCode":"ACCOUNT",
            "loginName":"账号登录",
            "sortOrder":2,
            "enabled":true
          },
          // {
          //   "i18n":null,
          //   "id":"6",
          //   "loginIcon":"",
          //   "client":"WEB",
          //   "cloudEnv":"ALY",
          //   "loginCode":"TRIAL",
          //   "loginName":"立即体验",
          //   "sortOrder":3,
          //   "enabled":true
          // },
          // {
          //   "i18n":null,
          //   "id":"8",
          //   "loginIcon":"",
          //   "client":"WEB",
          //   "cloudEnv":"ALY",
          //   "loginCode":"WECHAT",
          //   "loginName":"企业微信",
          //   "sortOrder":5,
          //   "enabled":true
          // },
          {
            "i18n":null,
            "id":"7",
            "loginIcon":"",
            "client":"WEB",
            "cloudEnv":"ALY",
            "loginCode":"ENTERPRISE",
            "loginName":"企业登录",
            "sortOrder":4,
            "enabled":true
          }
        ]
      };
      let data = {
        hasCodeLogin: false,
        loginWayList: [],
        codeLoginMessage: messages('login.key48')/*二维码登录*/,
      };
      // if(resData.loginConfigs && resData.loginConfigs.length){
        resData.loginConfigs.map(item => {
          if (item.loginCode === "QR_CODE") {
            data.hasCodeLogin = true;
            data.codeLoginMessage = item.loginName;
          }else {
            let param = loginWayAllObj[item.loginCode](self);
            param.message = item.loginName;
            if(item.loginIcon){
              param.icon = item.loginIcon
            }

            data.loginWayList.push(param);
          }
        });
      // }else{
      //   data.loginWayList.push(loginWayAllObj["ACCOUNT"](self));
      // }
      data.loginWayList[0].active = true;


        /*if(pathLoginWay && loginWayAllObj[pathLoginWay]){
          let arr = data.loginWayList.filter(item => item.key === pathLoginWay);
          if(arr && arr.length){
            data.loginWayList.filter(item => item.key === pathLoginWay)[0].active = true
          }else{
            data.loginWayList[0].active = true;
          }
        }else{
          data.loginWayList[0].active = true;
        }*/

      resolve(data)
    }).catch(err => {
      //errorMessage(err.response);
      reject(err);
    })

  },

  //获取企业登录时的协议内容
  getTenantProtocol(header) {
    return axios({
      url: config.baseUrl + "/api/tenant/protocol/heliosTenant",
      method: "GET",
      headers: {
        'x-helios-client': 'web',
        'Content-Type': "text/plain;charset=utf-8",
        'x-helios-tenant': header,
      },
    }).catch(err => {
        errorMessage(err.response);
        throw err;
      })
  },
}
